<template>
  <div class="distribution-statistics">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分销统计</span>
        </div>
      </template>

      <!-- 数据概览 -->
      <el-row :gutter="20" style="margin-bottom: 30px;">
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-value">¥{{ statistics.total_commission }}</div>
              <div class="overview-label">累计佣金</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-value">¥{{ statistics.withdrawable_commission }}</div>
              <div class="overview-label">可提现佣金</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-value">{{ statistics.distributor_count }}</div>
              <div class="overview-label">分销员数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="overview-content">
              <div class="overview-value">{{ statistics.order_count }}</div>
              <div class="overview-label">分销订单数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" style="margin-bottom: 30px;">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>佣金趋势（近30天）</span>
            </div>
            <div ref="commissionChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>分销员增长趋势（近30天）</span>
            </div>
            <div ref="distributorChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 排行榜 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>佣金排行榜（Top 10）</span>
            </div>
            <el-table :data="commissionRanking" style="width: 100%">
              <el-table-column prop="rank" label="排名" width="80" />
              <el-table-column label="分销员">
                <template #default="scope">
                  <div style="display: flex; align-items: center;">
                    <el-avatar
                      :size="30"
                      :src="VITE_URL + '/storage/' + scope.row.avatar"
                      style="margin-right: 10px;"
                    />
                    <span>{{ scope.row.customer_name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="total_commission" label="佣金金额" width="120">
                <template #default="scope">
                  ¥{{ scope.row.total_commission }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>订单排行榜（Top 10）</span>
            </div>
            <el-table :data="orderRanking" style="width: 100%">
              <el-table-column prop="rank" label="排名" width="80" />
              <el-table-column label="分销员">
                <template #default="scope">
                  <div style="display: flex; align-items: center;">
                    <el-avatar
                      :size="30"
                      :src="VITE_URL + '/storage/' + scope.row.avatar"
                      style="margin-right: 10px;"
                    />
                    <span>{{ scope.row.customer_name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="order_count" label="订单数量" width="120" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
// @ts-ignore
import * as echarts from 'echarts'

const VITE_URL = (window as any).VITE_URL

// 统计数据
const statistics = ref({
  total_commission: 0,
  withdrawable_commission: 0,
  distributor_count: 0,
  order_count: 0
})

// 排行榜数据
const commissionRanking = ref([])
const orderRanking = ref([])

// 图表实例
let commissionChart: any = null
let distributorChart: any = null

// 获取统计数据
const getStatistics = async () => {
  try {
    const url = `${VITE_URL}/admin.distribution/statistics`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      statistics.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

// 获取佣金排行榜
const getCommissionRanking = async () => {
  try {
    const url = `${VITE_URL}/admin.distribution/commission_ranking`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      commissionRanking.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取佣金排行榜失败')
  }
}

// 获取订单排行榜
const getOrderRanking = async () => {
  try {
    const url = `${VITE_URL}/admin.distribution/order_ranking`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      orderRanking.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取订单排行榜失败')
  }
}

// 初始化图表
const initCharts = () => {
  // 佣金趋势图表
  const commissionChartDom = document.getElementById('commissionChart')
  if (commissionChartDom) {
    commissionChart = echarts.init(commissionChartDom)
    commissionChart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['10-01', '10-05', '10-10', '10-15', '10-20', '10-25', '10-30']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'line',
        smooth: true
      }]
    })
  }

  // 分销员增长趋势图表
  const distributorChartDom = document.getElementById('distributorChart')
  if (distributorChartDom) {
    distributorChart = echarts.init(distributorChartDom)
    distributorChart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['10-01', '10-05', '10-10', '10-15', '10-20', '10-25', '10-30']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: [10, 25, 35, 40, 55, 70, 85],
        type: 'line',
        smooth: true
      }]
    })
  }
}

// 窗口大小改变时重置图表
const handleResize = () => {
  if (commissionChart) {
    commissionChart.resize()
  }
  if (distributorChart) {
    distributorChart.resize()
  }
}

onMounted(() => {
  getStatistics()
  getCommissionRanking()
  getOrderRanking()
  initCharts()
  
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  
  if (commissionChart) {
    commissionChart.dispose()
  }
  if (distributorChart) {
    distributorChart.dispose()
  }
})
</script>

<style scoped>
.distribution-statistics {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-card {
  text-align: center;
}

.overview-content {
  padding: 20px 0;
}

.overview-value {
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 5px;
}

.overview-label {
  color: #999;
}
</style>